#include <string.h>
#include <iostream>
using std::cout;
using std::endl;

class String
{
public:
	String();
	String(const char *pstr);
	String(const String &rhs);

    String(String && rhs)
    : _pstr(rhs._pstr)
    {
        cout << "String(String&&)" << endl;
        rhs._pstr = nullptr;
    }

	String &operator=(const String &rhs);
	~String();
	void print();
    size_t length() const;
    const char * c_str() const;

private:
	char * _pstr;
};

String::String()
: _pstr(new char[1]())
{
    cout << "String()" << endl;
}

//还是需要将原本的拷贝构造留下了，
//处理复制左值内容的情况
String::String(const char * pstr)
: _pstr(new char[strlen(pstr) + 1]())
{
    cout << "String(const char *) " << endl;
    strcpy(_pstr,pstr);
}

String::String(const String & rhs)
: _pstr(new char[strlen(rhs._pstr) + 1]())
{
    cout << "String(const String &)" << endl;
    strcpy(_pstr,rhs._pstr);
}

String & String::operator=(const String &rhs){
    if(this != &rhs){
        delete [] _pstr;
        _pstr = new char[strlen(rhs._pstr)]();
        strcpy(_pstr,rhs._pstr);
        cout << "String& operator=(const String&)" << endl;
    }
    return *this;
}

String::~String(){
    if(_pstr){
        delete [] _pstr;
        _pstr = nullptr;
    }
    cout << "~String()" << endl;
}

void String::print(){
    cout << _pstr << endl;
}
    
size_t String::length() const{
    cout << strlen(_pstr) << endl;
}
    
const char * String::c_str() const{
    return _pstr;
}


void test0(){
    //构造
    String s1("hello");
    //拷贝构造
    String s2 = s1;
    //先构造，再拷贝构造
    //利用"hello"这个字符串创建了一个匿名对象
    //并复制给了s3
    //这一步实际上new了两次
    String s3 = "hello";
}



int main()
{
    test0();
	return 0;
}

